/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package we.session;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import we.common.CDebug;
import we.dispatcher.CCoreServer;
import we.dispatcher.CPacketWriter;
import we.dispatcher.IDisposable;
import we.dispatcher.packet.CSentPacket;

/**
 *
 * @author ADMIN
 */
public class CSession implements IDisposable
{

    private Map<Object, Object> map;
    private SelectionKey selectionKey;

    public CSession(SelectionKey selectionKey)
    {
        map = new HashMap<Object, Object>();
        this.selectionKey = selectionKey;
    }

    public boolean containAttribute(Object key)
    {
        return map.containsKey(key);
    }
    
    public String GetIP() 
    {
        try
        {
            return ((SocketChannel) selectionKey.channel()).getLocalAddress().toString();
        } catch (IOException ex)
        {
            CDebug.Error(this, ex);
            return "";
        }
    }

    public void setAttribute(Object key, Object value)
    {
        map.put(key, value);
    }

    public Object getAttribute(String key)
    {
        return map.get(key);
    }

    public Object removeAttribute(Object key)
    {
        return map.remove(key);
    }

    public boolean removeAttribute(Object key, Object value)
    {
        Object tmp = map.get(key);
        if (tmp.equals(value))
        {
            map.remove(key);
            return true;
        } else
        {
            return false;
        }
    }

    public boolean replaceAttribute(Object key, Object oldValue, Object newValue)
    {
        return false;
    }

    public boolean close()
    {        
        CCoreServer.CloseChannel(selectionKey);
        return true;
    }

    public void Send(byte[] bb)
    {
        CCoreServer.instance().sendMsg(selectionKey, bb);
    }

    public void Send(ByteBuffer bb)
    {
        CCoreServer.instance().SendMsg(selectionKey, bb);
    }
    
    public void Send(CPacketWriter writer)
    {
        CCoreServer.instance().SendMsg(selectionKey, writer.buffer());
    }

    public void write(CSentPacket packet)
    {
        CCoreServer.instance().SendMsg(selectionKey, packet.getBuffer());
    }

    @Override
    public void dispose()
    {
        map = null;
        selectionKey = null;
    }
}
